{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 载入文件\n",
    "path = \"示例文本文件.txt\"\n",
    "open(file=path, mode=\"r\", encoding=\"utf-8\")  # 只读模式\n",
    "open(file=path, mode=\"a\", encoding=\"utf-8\")  # 追加模式\n",
    "open(file=path, mode=\"w\", encoding=\"utf-8\")  # 覆盖写入模式\n",
    "open(file=path, mode=\"+\", encoding=\"utf-8\")  # 可读可写模式\n",
    "open(file=path, mode=\"rb\", encoding=\"utf-8\")  # 二进制读取模式,用于非文本文件\n",
    "open(file=path, mode=\"wb\", encoding=\"utf-8\")  # 二进制写入模式,用于非文本文件"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 读取文件\n",
    "\n",
    "# 以下是安全的写法\n",
    "f = None  # 先定义一个文件标识符, 确保后续的finally语句可以正常执行\n",
    "try:\n",
    "    path = \"示例文本文件.txt\"\n",
    "    f = open(file=path, mode=\"r\", encoding=\"utf-8\")  # 通过open函数打开文件\n",
    "    textList = f.read()  # 读取文件所有内容\n",
    "    print(textList)\n",
    "except Exception as e:\n",
    "    print(e)\n",
    "finally:  # 无论是否打开文件都把文件关闭\n",
    "    if f:\n",
    "        f.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 读取部分文本\n",
    "\n",
    "f = None\n",
    "try:\n",
    "    path = \"示例文本文件.txt\"\n",
    "    f = open(file=path, mode=\"r\", encoding=\"utf-8\")\n",
    "    textList = f.read(10)  # 先读取10个字符\n",
    "    print(textList)\n",
    "    textList = f.read(10)  # 再读取10个字符\n",
    "    print(textList)\n",
    "    # 这里存在一个游标的概念,read方法每次读取都会把游标移动到结束的位置,下次读取会从上次结束的位置开始\n",
    "except Exception as e:\n",
    "    print(e)\n",
    "finally:\n",
    "    if f:\n",
    "        f.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 批量截取特定数量字符\n",
    "\n",
    "f = None\n",
    "try:\n",
    "    path = \"示例文本文件.txt\"\n",
    "    f = open(file=path, mode=\"r\", encoding=\"utf-8\")\n",
    "    while True:\n",
    "        textList = f.read(10)  # 10个字符为一组有序读取\n",
    "        print(textList)\n",
    "        if not textList:  # 如果没有了则break循环\n",
    "            break\n",
    "except Exception as e:\n",
    "    print(e)\n",
    "finally:\n",
    "    if f:\n",
    "        f.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 读一行\n",
    "\n",
    "f = None\n",
    "try:\n",
    "    path = \"示例文本文件.txt\"\n",
    "    f = open(file=path, mode=\"r\", encoding=\"utf-8\")\n",
    "    textList = f.readline()\n",
    "    print(textList)\n",
    "    textList = f.readline()\n",
    "    print(textList)\n",
    "except Exception as e:\n",
    "    print(e)\n",
    "finally:\n",
    "    if f:\n",
    "        f.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "SubFunction Was Imported\n",
      "altgraph @ file:///AppleInternal/Library/BuildRoots/2c89a47b-9dd5-11ef-938f-6e654a286000/Library/Caches/com.apple.xbs/Sources/python3/altgraph-0.17.2-py2.py3-none-any.whl\n",
      "\n",
      "appnope==0.1.4\n",
      "\n",
      "asttokens==3.0.0\n",
      "\n",
      "comm==0.2.2\n",
      "\n",
      "debugpy==1.8.9\n",
      "\n",
      "decorator==5.1.1\n",
      "\n",
      "exceptiongroup==1.2.2\n",
      "\n",
      "executing==2.1.0\n",
      "\n",
      "future @ file:///AppleInternal/Library/BuildRoots/2c89a47b-9dd5-11ef-938f-6e654a286000/Library/Caches/com.apple.xbs/Sources/python3/future-0.18.2-py3-none-any.whl\n",
      "\n",
      "importlib_metadata==8.5.0\n",
      "\n",
      "ipykernel==6.29.5\n",
      "\n",
      "ipython==8.18.1\n",
      "\n",
      "jedi==0.19.2\n",
      "\n",
      "jupyter_client==8.6.3\n",
      "\n",
      "jupyter_core==5.7.2\n",
      "\n",
      "macholib @ file:///AppleInternal/Library/BuildRoots/2c89a47b-9dd5-11ef-938f-6e654a286000/Library/Caches/com.apple.xbs/Sources/python3/macholib-1.15.2-py2.py3-none-any.whl\n",
      "\n",
      "matplotlib-inline==0.1.7\n",
      "\n",
      "nest-asyncio==1.6.0\n",
      "\n",
      "packaging==24.2\n",
      "\n",
      "parso==0.8.4\n",
      "\n",
      "pexpect==4.9.0\n",
      "\n",
      "platformdirs==4.3.6\n",
      "\n",
      "prompt_toolkit==3.0.48\n",
      "\n",
      "psutil==6.1.0\n",
      "\n",
      "ptyprocess==0.7.0\n",
      "\n",
      "pure_eval==0.2.3\n",
      "\n",
      "Pygments==2.18.0\n",
      "\n",
      "python-dateutil==2.9.0.post0\n",
      "\n",
      "pyzmq==26.2.0\n",
      "\n",
      "six @ file:///AppleInternal/Library/BuildRoots/2c89a47b-9dd5-11ef-938f-6e654a286000/Library/Caches/com.apple.xbs/Sources/python3/six-1.15.0-py2.py3-none-any.whl\n",
      "\n",
      "stack-data==0.6.3\n",
      "\n",
      "tornado==6.4.2\n",
      "\n",
      "traitlets==5.14.3\n",
      "\n",
      "typing_extensions==4.12.2\n",
      "\n",
      "wcwidth==0.2.13\n",
      "\n",
      "zipp==3.21.0\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# 将文件按行传入list\n",
    "from SubFunc import printList\n",
    "\n",
    "f = None\n",
    "try:\n",
    "    path = \"示例读取文件.txt\"\n",
    "    f = open(file=path, mode=\"r\", encoding=\"utf-8\")\n",
    "    textList: list[str] = f.readlines()\n",
    "    printList(textList)\n",
    "except Exception as e:\n",
    "    print(e)\n",
    "finally:\n",
    "    if f:\n",
    "        f.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 写入内容\n",
    "f = None\n",
    "try:\n",
    "    path = \"示例写入文件.txt\"  # 如果文件不存在则会自动创建\n",
    "    f = open(file=path, mode=\"w\", encoding=\"utf-8\")\n",
    "    f.write(\"Hello\\n\")\n",
    "    f.write(\"World!\\n\")  # 这里也存在游标的概念,一直write就会一直追加,直到close\n",
    "except Exception as e:\n",
    "    print(e)\n",
    "finally:\n",
    "    if f:\n",
    "        f.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 按列表写入\n",
    "f = None\n",
    "try:\n",
    "    path = \"示例写入文件.txt\"\n",
    "    f = open(file=path, mode=\"w\", encoding=\"utf-8\")\n",
    "    f.writelines(\n",
    "        [\"aaa\", \"bbb\", \"ccc\"]\n",
    "    )  # 实际并没有写成三行,而是直接在一行内写入所有列表的元素\n",
    "except Exception as e:\n",
    "    print(e)\n",
    "finally:\n",
    "    if f:\n",
    "        f.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "altgraph @ file:///AppleInternal/Library/BuildRoots/2c89a47b-9dd5-11ef-938f-6e654a286000/Library/Caches/com.apple.xbs/Sources/python3/altgraph-0.17.2-py2.py3-none-any.whl\n",
      "\n",
      "appnope==0.1.4\n",
      "\n",
      "asttokens==3.0.0\n",
      "\n",
      "comm==0.2.2\n",
      "\n",
      "debugpy==1.8.9\n",
      "\n",
      "decorator==5.1.1\n",
      "\n",
      "exceptiongroup==1.2.2\n",
      "\n",
      "executing==2.1.0\n",
      "\n",
      "future @ file:///AppleInternal/Library/BuildRoots/2c89a47b-9dd5-11ef-938f-6e654a286000/Library/Caches/com.apple.xbs/Sources/python3/future-0.18.2-py3-none-any.whl\n",
      "\n",
      "importlib_metadata==8.5.0\n",
      "\n",
      "ipykernel==6.29.5\n",
      "\n",
      "ipython==8.18.1\n",
      "\n",
      "jedi==0.19.2\n",
      "\n",
      "jupyter_client==8.6.3\n",
      "\n",
      "jupyter_core==5.7.2\n",
      "\n",
      "macholib @ file:///AppleInternal/Library/BuildRoots/2c89a47b-9dd5-11ef-938f-6e654a286000/Library/Caches/com.apple.xbs/Sources/python3/macholib-1.15.2-py2.py3-none-any.whl\n",
      "\n",
      "matplotlib-inline==0.1.7\n",
      "\n",
      "nest-asyncio==1.6.0\n",
      "\n",
      "packaging==24.2\n",
      "\n",
      "parso==0.8.4\n",
      "\n",
      "pexpect==4.9.0\n",
      "\n",
      "platformdirs==4.3.6\n",
      "\n",
      "prompt_toolkit==3.0.48\n",
      "\n",
      "psutil==6.1.0\n",
      "\n",
      "ptyprocess==0.7.0\n",
      "\n",
      "pure_eval==0.2.3\n",
      "\n",
      "Pygments==2.18.0\n",
      "\n",
      "python-dateutil==2.9.0.post0\n",
      "\n",
      "pyzmq==26.2.0\n",
      "\n",
      "six @ file:///AppleInternal/Library/BuildRoots/2c89a47b-9dd5-11ef-938f-6e654a286000/Library/Caches/com.apple.xbs/Sources/python3/six-1.15.0-py2.py3-none-any.whl\n",
      "\n",
      "stack-data==0.6.3\n",
      "\n",
      "tornado==6.4.2\n",
      "\n",
      "traitlets==5.14.3\n",
      "\n",
      "typing_extensions==4.12.2\n",
      "\n",
      "wcwidth==0.2.13\n",
      "\n",
      "zipp==3.21.0\n",
      "\n",
      "False\n",
      "True\n"
     ]
    }
   ],
   "source": [
    "# 使用with进行上下文管理\n",
    "from SubFunc import printList\n",
    "\n",
    "f = None\n",
    "path = \"示例读取文件.txt\"\n",
    "with open(path, \"r\", encoding=\"utf-8\") as f:  # 通过with语句打开文件,不需要手动关闭文件\n",
    "    print(f.closed)  # 在with语句内文件是未关闭的\n",
    "    textList = f.readlines()\n",
    "    printList(textList)\n",
    "\n",
    "print(f.closed)  # 在with语句外文件是已关闭的"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "posix.uname_result(sysname='Darwin', nodename='tanqingwendeMacBook-Pro.local', release='24.2.0', version='Darwin Kernel Version 24.2.0: Fri Dec  6 19:01:59 PST 2024; root:xnu-11215.61.5~2/RELEASE_ARM64_T6000', machine='arm64')\n",
      "8\n",
      "/Users/tanqingwen/Desktop/学习-Python基础\n",
      "学习-Python基础\n",
      "朴朴超市预算拆解.pdf\n",
      ".DS_Store\n",
      "小象超市预算拆解.pdf\n",
      ".localized\n",
      "钱大妈预算分解.pdf\n",
      "截屏2024-12-31 17.01.11.png\n",
      "截屏2024-12-31 18.49.01.png\n",
      "截屏2024-12-31 18.27.40.png\n",
      "新领域预算分解.pdf\n",
      "截屏2024-12-20 20.02.10.png\n",
      "截屏2024-12-31 17.24.04.png\n",
      "飞书认证申请公函模板-谭清文.docx\n",
      "待找出处\n"
     ]
    }
   ],
   "source": [
    "# OS模块获取系统信息\n",
    "import os\n",
    "\n",
    "print(os.uname())  # 获取系统信息"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# OS模块获取线程数\n",
    "import os\n",
    "\n",
    "print(os.cpu_count())  # 获取CPU的线程数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# OS模块重命名文件\n",
    "import os\n",
    "\n",
    "os.rename(\"\", \"\")  # 重命名文件,第一个参数是原文件名,第二个参数是新文件名"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# OS模块获取当前目录\n",
    "import os\n",
    "\n",
    "print(os.getcwd())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# OS模块获取当前目录下的文件列表\n",
    "import os\n",
    "\n",
    "printList(os.listdir(\".\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# OS模块获取上级目录下的文件列表\n",
    "import os\n",
    "\n",
    "printList(os.listdir(\"..\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n",
      "True\n"
     ]
    }
   ],
   "source": [
    "# 判断是否为文件或文件夹\n",
    "import os\n",
    "\n",
    "print(os.path.isfile(\"示例读取文件.txt\"))  # 判断是否是文件\n",
    "print(os.path.isdir(\"示例包\"))  # 判断是否是文件夹"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
